<template>
  <div>
    <!--引用表格-->
    <div class="treeBox">
      压资: <span class="red" style="margin-right: 20px;">{{ result.buyingPrice }}</span>
      余额: <span class="red">{{ result.balance }}</span>
    </div>
    <div class="treeBox" v-if="DingDanID && DingDanID != ''"> 当前为订单：【{{ DingDanID }}】发起代付！ </div>
    <!-- :rowSelection="rowSelection" -->
    <BasicTable @register="registerTable" @fetch-success="handleFetchSuccess">
      <!--插槽:table标题-->
      <!--操作栏-->
      <template #action="{ record }">
        <!-- 只有子行显示操作按钮 -->
        <TableAction v-if="isChildRow(record)" :actions="getTableAction(record)" style="{width: 400px;
          display: flex;
          flex-direction: column;
          margin:40px 0;}" />
        <span v-else>/</span>
      </template>
      <!--字段回显插槽-->
      <template v-slot:cardTypeId_dictText="{ record }">
        <span v-if="!isChildRow(record)">
          {{ record.cardTypeId_dictText ? record.cardTypeId_dictText : '--' }}
        </span>
        <span v-else>
          /
        </span>
      </template>
      <template v-slot:brandId_dictText="{ record }">
        <span v-if="!isChildRow(record)">
          {{ record.brandId_dictText ? record.brandId_dictText : '--' }}
        </span>
        <span v-else>
          /
        </span>
      </template>
      <template v-slot:cardSourceId_dictText="{ record }">
        <span v-if="!isChildRow(record)">
          {{ record.cardSourceId_dictText ? record.cardSourceId_dictText : '--' }}
        </span>
        <span v-else>
          /
        </span>
      </template>


      <template v-slot:discount="{ record }">
        <span v-if="isChildRow(record)">
          {{ record.discount ? record.discount + '%' : '--' }}
        </span>
        <span v-else>
          {{ record.discount ? record.discount + '%' : '--' }}
        </span>
      </template>
      <template v-slot:memberName="{ record }">
        <span v-if="isChildRow(record)">
          {{ record.memberName ? record.memberName : '--' }}
        </span>
        <span v-else>
          /
        </span>
      </template>
      <template v-slot:memberPhone="{ record }">
        <span v-if="isChildRow(record)">
          {{ record.memberPhone ? record.memberPhone : '--' }}
        </span>
        <span v-else>
          /
        </span>
      </template>
      <template v-slot:buyingPrice="{ record }">
        <span v-if="isChildRow(record)">
          {{ record.buyingPrice ? record.buyingPrice : '--' }}
        </span>
        <span v-else>
          {{ record.buyingPrice ? record.buyingPrice : '--' }}
        </span>
      </template>
      <template v-slot:remark="{ record }">
        <div v-if="isChildRow(record)">
          <span v-if="!editingRemarkId || editingRemarkId !== record.id" @dblclick="startEditRemark(record)"
            style="cursor: pointer;user-select: none;">
            {{ record.remark ? record.remark : '--' }}
          </span>
          <a-input v-else v-model:value="editRemarkValue" @blur="finishEditRemark(record.id)"
            @keydown.enter="finishEditRemark(record.id)" @keydown.esc="cancelEditRemark" ref="remarkInput"
            style="width: 200px; margin-top: -5px;" autoFocus />
        </div>
        <span v-else>
          /
        </span>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <SubstituteModal2 @register="registerModal2" @success="handleSuccess"></SubstituteModal2>
    <a-modal v-model:visible="visible" title="操作记录" :footer="null" :width="1200">
      <a-table :columns="columns2" :data-source="dataSource" bordered :pagination="pagination"
        @change="handleTableChange" style="padding: 10px">
      </a-table>
    </a-modal>
    <a-modal v-model:visible="visible2" title="代付" :footer="null" :width="800">
      <a-form :model="formState" name="basic" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" autocomplete="off"
        @finish="onFinish" @finishFailed="onFinishFailed" class="myform">
        <a-form-item label="代付金额" name="amount" :rules="[{ required: true, message: '请输入代付金额' }]">
          <a-input v-model:value="formState.amount" type="number" />
        </a-form-item>

        <a-form-item label="备注" name="remark">
          <a-input v-model:value="formState.remark" />
        </a-form-item>

        <a-form-item :wrapper-col="{ offset: 20, span: 2 }">
          <a-button type="primary" html-type="submit" class="myitem">提交</a-button>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script lang="ts" name="card-substitute" setup>
import { ref, reactive, computed, unref, defineComponent, nextTick } from 'vue';
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage';
import SubstituteModal2 from './components/SubstituteModal2.vue';
import { columns, searchFormSchema, superQuerySchema, columns2 } from './Substitute.data';
import { list, deleteOne, batchDelete, getImportUrl, getExportUrl, recordList, substitute, getFund, editRemark } from './Substitute.api';
import { downloadFile } from '/@/utils/common/renderUtils';
import { useUserStore } from '/@/store/modules/user';
import type { TableProps } from 'ant-design-vue';
import { useRoute } from 'vue-router';
const route = useRoute();
const queryParam = reactive<any>({});
const checkedKeys = ref<Array<string | number>>([]);
const userStore = useUserStore();
const visible = ref<boolean>(false);
const visible2 = ref<boolean>(false);

const data = ref<any>([]);
const ID = ref('');
const DingDanID = ref('');
const result = ref('');
//注册model
const [registerModal2, { openModal: openModal2 }] = useModal();
//注册table数据
const { prefixCls, tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '',
    api: list,
    columns,
    rowKey: 'brandId',
    canResize: false,
    // 启用树形表格模式
    isTreeTable: true,
    // 指定子节点字段名
    childrenColumnName: 'children',
    // 配置展开图标
    expandIconColumnIndex: 0,
    formConfig: {
      //labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      showAdvancedButton: true,
      fieldMapToNumber: [],
      fieldMapToTime: [],
    },
    actionColumn: {
      width: 120,
      fixed: 'right',
    },
    beforeFetch: (params) => {
      params.orderNo = DingDanID.value;
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: '代付',
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess,
  },
});

const dataSource = ref(data);
// 使用 ref 定义可写的分页状态
const pagination = ref({
  total: 20,
  pageNo: 1,
  pageSize: 10,
});

// 判断是否为子行
function isChildRow(record) {
  // console.log(record.memberName);
  return record.memberName;
}

interface FormState {
  amount: number;
  orderNo: string;
  remark: string;
  substituteId: string;
}

const formState = reactive<FormState>({
  amount: 0,
  orderNo: '',
  remark: '',
  substituteId: '',
});

getFund().then((res) => {
  result.value = res;
});
const onFinish = (values: any) => {
  console.log('Success:', formState);
  substitute(formState).then((res) => {
    formState.amount = 0;
    formState.remark = '';
    formState.substituteId = '';
    visible2.value = false;
    reload();
  });
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

function handleTableChange(p) {
  console.log('点击分页', p);
  pagination.value.pageNo = p.current;
  pagination.value.pageSize = p.pageSize;
  getList();
}

function getList() {
  console.log({ substituteId: ID.value, pageNo: pagination.value.pageNo, pageSize: pagination.value.pageSize });

  recordList({ substituteId: ID.value, pageNo: pagination.value.pageNo, pageSize: pagination.value.pageSize }).then((res) => {
    data.value = res.records;
    console.log('res', res);
    pagination.value.total = res.total;
    console.log('data', data.value);
  });

  visible.value = true;
}
const [registerTable, { reload, expandAll }, { rowSelection, selectedRowKeys }] = tableContext;

function handleFetchSuccess() {
  nextTick(() => {
    expandAll?.();
  });
}

if (route.query.id) {
  formState.orderNo = route.query.id;
  DingDanID.value = route.query.id;
}
console.log('DingDanID', DingDanID.value);
/**
 * 新增事件
 */
function handleAdd() {
  openModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
function handleEdit2(record: Recordable) {
  openModal2(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
function handleEdit3(record: Recordable) {
  formState.substituteId = record.id;
  visible2.value = true;
}

/**
 * 详情
 */
function handleDetail(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: false,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 批量删除事件
 */
async function batchHandleDelete() {
  await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}
function setId(record) {
  ID.value = record.id;
  getList();
}
/**
 * 操作栏
 */
function getTableAction(record) {
  console.log('DingDanIDvaluevaluevaluevalue', DingDanID.value);

  return [
    {
      label: '操作记录',
      onClick: setId.bind(null, record),
    },
    {
      label: '充值',
      onClick: handleEdit2.bind(null, record),
      ifShow: (_action) => {
        return DingDanID.value === '' ? true : false;
      },
    },
    {
      label: '代付',
      onClick: handleEdit3.bind(null, record),
      ifShow: (_action) => {
        return DingDanID.value === '' ? false : true;
      },
    },
    {
      label: '删除',
      popConfirm: {
        title: '是否确认删除',
        confirm: handleDelete.bind(null, record),
        placement: 'topLeft',
      },
    },
  ];
}
// 编辑备注相关变量
const editingRemarkId = ref<string | null>(null);
const editRemarkValue = ref<string>('');
const remarkInput = ref<any>(null);

// 开始编辑备注
function startEditRemark(record: any) {
  editingRemarkId.value = record.id;
  editRemarkValue.value = record.remark || '';
  // 在下一个DOM更新周期后聚焦输入框
  nextTick(() => {
    if (remarkInput.value) {
      remarkInput.value.focus();
    }
  });
}

// 完成编辑备注
async function finishEditRemark(id: string) {
  try {
    // 调用修改备注的API
    await editRemark({ id, remark: editRemarkValue.value });
    // 刷新表格数据
    reload();
  } catch (error) {
    console.error('修改备注失败:', error);
  } finally {
    // 无论成功失败都退出编辑状态
    editingRemarkId.value = null;
  }
}

// 取消编辑备注
function cancelEditRemark() {
  editingRemarkId.value = null;
}
</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-table) {
  min-height: 700px;
}

:deep(.ant-pagination) {
  margin-right: 10px !important;
}

.treeBox {
  margin: 10px;
  background: #fff;
  padding: 20px;
  box-sizing: border-box;
  background-color: #fdf6ec;
  color: #e6a23c;
}

.myform {
  margin: 40px 0;
}

.myitem {
  margin: 40px 0;
}
</style>
